/******************************************************************************************************
Copyright (C) 2013 Mestrelab Research S.L. All rights reserved.

This file is part of the Mnova scripting toolkit.

Authorized users of MNova Software may use this file freely, but this file is provided AS IS
with NO WARRANTY OF ANY KIND, INCLUDING THE WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS
FOR A PARTICULAR PURPOSE.
*****************************************************************************************************/

/*globals Application, DBPlugin, qsTr, MessageBox, ProgressDialog, print*/
/*jslint plusplus: true, indent: 4*/

function dbBrowserExample() {
    "use strict";
    var hits, hit, h, i, recordIds, records, r, rid, record, items, item, fieldNames, f,
        db = DBPlugin.client,
        progress = new ProgressDialog();

    // Choose database
    Application.mainWindow.doAction("dbDatabaseOpen");
    if (!(db.connected() && db.database.length > 0)) {
        return;
    }

    // Do a search 
    print("Searching for '-' ...");
    hits = DBPlugin.search(db, "-", "TEXT", "Molecule");
    MessageBox.information(qsTr("{0} hits found.").format(hits.length));

    // Collect record ids 
    recordIds = [];
    for (h = 0; h < hits.length; h++) {
        hit = hits.at(h);
        print(" Hit " + h + ": Record=" + hit.recordId() + " Item=" + hit.itemId() + " Score=" + hit.score() + " (" + hit.toString() + ")");
        if (recordIds.indexOf(hit.recordId()) < 0) {
            recordIds.push(hit.recordId());
        }
    }

    // Retrieve records
    records = [];
    progress.setRange(0, recordIds.length);
    progress.show();
    for (r = 0; r < recordIds.length && !progress.wasCanceled; r++) {
        rid = recordIds[r];
        progress.value = r;
        progress.labelText = qsTr("Retrieving record {0} ({1} of {2})...").format(rid, r + 1, recordIds.length);
        Application.mainWindow.processEvents();
        print("Retrieving record " + rid + "...");
        record = DBPlugin.getRecord(DBPlugin.client, rid, false);
        //print(record);
        items = record.items();
        print("Retrieved " + items.length + " items from record " + record.url() + ".");
        for (i = 0; i < items.length; i++) {
            item = items[i];
            //print(item);
            //print(JSON.stringify(item.fieldNames()));
            fieldNames = item.fieldNames();
            for (f = 0; f < fieldNames.length; f++) {
                print("     " + f + ":" + fieldNames[f] + ":" + item.field(fieldNames[f]));
            }
        }
        records.push(record);
    }
    progress.close();
    DBPlugin.createBrowser(records);
}
